/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-getCar
*
* @File name : GetCarService.java
*
* @Author : Administrator
*
* @Date : 2017年6月30日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年6月30日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.getCar.service;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventGetSendToPayDTO;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.DateUtil;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.service.getCar.constant.GetCarConstant;
import com.yonyou.gmmc.service.getCar.dao.TmDealerMapper;
import com.yonyou.gmmc.service.getCar.dao.TtEtcoMapper;
import com.yonyou.gmmc.service.getCar.dao.TtMaintenanceRecordMapper;
import com.yonyou.gmmc.service.getCar.dao.TtReservationMapper;
import com.yonyou.gmmc.service.getCar.entity.GscReservation;
import com.yonyou.gmmc.service.getCar.model.TmDealer;
import com.yonyou.gmmc.service.getCar.model.TtEtco;
import com.yonyou.gmmc.service.getCar.model.TtMaintenanceRecord;
import com.yonyou.gmmc.service.getCar.model.TtReservation;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @author Administrator 
 * @date 2017年6月30日
 */

@Transactional
@Service("getCarService")
public class GetCarService {

	private Logger logger = Logger.getLogger(GetCarService.class);
	@Autowired
	private TtEtcoMapper ttEtcoMapper;
	@Autowired
	private TmDealerMapper tmDealerMapper;
	@Autowired
	private TtReservationMapper ttReservationMapper;
	@Autowired
	private TtMaintenanceRecordMapper ttMaintenanceRecordMapper;
	@Autowired
    private IdealerssService idealerssService;
	@Autowired
	private BaseService eventService;
	@Value("${IDEALERSS_URL}")
	private String idealerurl;
	@Value("${SECRET_KEY}")
	private String secretKey;
	@Value("${SECRET_KEY_STATUS}")
	private String secretKeyStatus;
	@Value("${CHANNEL}")
	private String channel;
	@Value("${IDEALERCODE}")
	private String idealerCode;
	
	//微信支付后跳转的3个url
	@Value("${OKURL}")
	private String okUrl;
	@Value("${CANCEURL}")
	private String canceUrl;
	@Value("${FAILURL}")
	private String failUrl;
	
	public Map<String, Object> isCanGetSendCar(String dealerCode){
		logger.info("GetCarService.findGscTime==>start...");
		Map<String, Object> result = new HashMap<>();
		TmDealer d = new TmDealer();
		d.setDealerCode(dealerCode);
		d.setGscDealerFlag((short) 1);
		TmDealer dealer = tmDealerMapper.selectOne(d);
		if(dealer==null){
			result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "该经销商未开通去送车服务");
		}else{
			result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
        	result.put(ResultMsgConstants.ERR_MSG, "该经销商已开通去送车服务");
		}
		return result;
	}
	private Map<String, Object>  mqUserPoints(TtEtco etco,EventBizStep eventBizStep) {
		logger.info("向MQ发送通知>>>>>>>>>>>>>>>>>>>>");
		Map<String, Object> result = new HashMap<>();
		result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		BizEvent event = new BizEvent();
		String carPhone = ttEtcoMapper.findCarPhone(etco.getCreatorId());
		String deductPoints = etco.getReferprice().toString();
		EventGetSendToPayDTO orderEventDto = new EventGetSendToPayDTO();
        orderEventDto.setPhone(carPhone);
        logger.info("下单的手机号——" + orderEventDto.getPhone());
        orderEventDto.setPointsNum(Long.valueOf(deductPoints));
        logger.info("订单需要扣减的金额——" + orderEventDto.getPointsNum());
        orderEventDto.setEtcoNo(etco.getPkEtcoId().toString());
        logger.info("订单号——" + etco.getPkEtcoId().toString());
        orderEventDto.setUserId(etco.getCreatorId());
        logger.info("下单的用户id——" + orderEventDto.getUserId());
        
        event.setEventKey("GetSendCar--"+orderEventDto.getEtcoNo()+"-"+DateUtil.formateDate(new Date(), "yyyyMMddHHmmss"));
        event.setEventBizType(EventBizType.IDEALER_ORDER);
        event.setEventBizStep(eventBizStep);
        event.setEventData(MapConverUtil.PO2Map(orderEventDto));
        
		String x = "";
		try {
			x = eventService.sendEvent2MQ(event);
		} catch (Exception e) {
			logger.info("向MQ发送通知异常:"+e.getMessage(),e);
			result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, e.getMessage());
            return result;
		}
        logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + x);
        if (x.indexOf("\"result\":\"200\"") >= 0) {
            logger.info("MQ接收成功........." );
            result.put(ResultMsgConstants.ERR_MSG, "MQ接收成功");
            return result;
        } else {
            logger.info("MQ接收失败............");
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "MQ接收失败");
            return result;
        }
	}
	/**
	 * 向idealer下单,并积分支付
	 * @param gscReservation
	 * @return
	 */
	public Map<String, Object> saveGetOrSendCar(String pkId){
		logger.info("GetCarService.findGscTime==>start...");
		Map<String, Object> result = new HashMap<>();
		
		result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		TtEtco etco = ttEtcoMapper.selectByPrimaryKey(Long.valueOf(pkId));
		Integer flag = etco.getGetsendFlag();// 取送类型
        String carPoints = "";
        Double userPoints = 0.0;
        Map<String, Object> resultMQ = new HashMap<>();
		if(!CheckUtil.NullOrEmpty(etco)){
			logger.info("用户类型为微信用户——开始扣分");
            carPoints = ttEtcoMapper.findCarPoints(etco.getCreatorId());
            if(!"".equals(carPoints)){
            	userPoints = Double.valueOf(carPoints);
            }
            if(userPoints<etco.getReferprice().doubleValue()){
            	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_POINTS);
            	result.put(ResultMsgConstants.ERR_MSG, "积分不足请选择其他支付方式");
                return result;
            }
            resultMQ = mqUserPoints(etco,EventBizStep.GETSEND_ORDER_SUBTRACT);
		}else{
			result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "订单不存在！");
            return result;
		}
        try {
            //向idealer下单
            Map<String, Object> getCarMap = new HashMap<>();
            // 渠道号默认设置
            // 业务服务类别
            getCarMap.put("serviceType", "10071001");
            // 经销商代码
            getCarMap.put("dealerCode", idealerCode);
            // 车牌号
            getCarMap.put("plateNumber", etco.getLicenseNo());
            // 经销商代码类型
            getCarMap.put("dealerType", "10081002");
            // 消息来源
            getCarMap.put("msgSrc", "10091001");
            // 来源单据类型
            getCarMap.put("billType", "10101001");
            // 支付类型
            getCarMap.put("payer", "10461001");
            getCarMap.put("msgSrcService", etco.getMsgSrcFlag());
            if(flag==10180001){
            	// 来源单据取送车 服务类型
                getCarMap.put("takeDeliveryType", "10481001");
                // 来源单据编号
                getCarMap.put("billNo", etco.getResnId());
            }else if(flag==10180002){
            	getCarMap.put("takeDeliveryType", "10481002");
            	// 来源单据编号
                getCarMap.put("billNo", etco.getOrderid());
            }else if(flag==10180003){
            	getCarMap.put("msgSrcService", "10180003");
            	getCarMap.put("takeDeliveryType", "10180003");
                getCarMap.put("billNo", "10180003");
            }
            // 取送车流水
            getCarMap.put("takeDeliveryId", pkId);
            // 优惠券编号
            getCarMap.put("coupon_No", "111");
            // 起始地
            getCarMap.put("startAddr", etco.getStartAddr());
            // 起始地联系人
            getCarMap.put("startLinkman", etco.getStartLinkman());
            // 起始地电话
            getCarMap.put("startPhone", etco.getStartPhone());
            // 目的地
            getCarMap.put("destAddr", etco.getDestAddr());
            // 目的地联系人
            getCarMap.put("destLinkman", etco.getDestLinkman());
            // 目的地电话
            getCarMap.put("destPhone", etco.getDestPhone());
            if(flag==10180003){
	            // 起始地联系人
	            getCarMap.put("startLinkman", "123");
	            // 目的地联系人
	            getCarMap.put("destLinkman", "111");
            }
            // getCarMap.put("startTime","2016-11-01 00:00:00");
            // 预约时间
            getCarMap.put("startTime", DateUtil.formateDate(etco.getWonderTime(), "yyyy-MM-dd HH:mm:ss"));
            // 下单人
            getCarMap.put("operator", etco.getCreatorId());
            // 发生时间
            getCarMap.put("occurtime", new Date().getTime());
            // 优惠券
            //getCarMap.put("couponNo", paramsMap.get("coupon_no"));

            logger.info("idealerRequest xiadan map = " + getCarMap);
            if ("1".equals(resultMQ.get("resultCode").toString())) {
            	String returnJsonCode = idealerssService.sendOrder(getCarMap);
                if (returnJsonCode != null && !"".equals(returnJsonCode)) {
                    JSONObject returnObject = JSONObject.fromObject(returnJsonCode);
                    if (returnObject != null && returnObject.get("code").equals(91200)) {

                        JSONObject resultMsg = JSONObject.fromObject(returnObject.get("data"));
                        String idealersId = resultMsg.get("idealersId")== null ? "" : resultMsg.get("idealersId").toString();
                        
                        TtEtco etc = new TtEtco();
                        etc.setIdealersid(Long.valueOf(idealersId));
                        etc.setGetsendStatus(Integer.valueOf(GetCarConstant.GETSEND_STATUS_10191002));
                        etc.setDef1("1");//积分支付1
                        Example ex = new Example(TtEtco.class);
                        Criteria  criteria = ex.createCriteria();
                        criteria.andEqualTo("pkEtcoId", pkId);
                        ttEtcoMapper.updateByExampleSelective(etc, ex);
                        //更新取送车按钮状态
                        updateGetSend(etco.getSrvOrderNo(),etco.getGetsendFlag());
                    } else {
                    	resultMQ = mqUserPoints(etco,EventBizStep.GETSEND_ORDER_ADD);
                    	logger.error("积分返还原因====>idealer报错：" + returnObject.get("message"));
                    	if ("1".equals(resultMQ.get("resultCode").toString())) {
                    		logger.error("积分返还成功====> ");
                    	}else{
                    		logger.error("积分返还失败====> " + resultMQ.get("errMsg"));
                    	}
                        result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
                    	result.put(ResultMsgConstants.ERR_MSG, returnObject.get("message"));
                        return result;
                    }
                }else{
                	resultMQ = mqUserPoints(etco,EventBizStep.GETSEND_ORDER_ADD);
                	logger.error("积分返还原因====>idealer返回结果：" + returnJsonCode);
                	if ("1".equals(resultMQ.get("resultCode").toString())) {
                		logger.error("积分返还成功====> ");
                	}else{
                		logger.error("积分返还失败====> " + resultMQ.get("errMsg"));
                	}
                	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
                	result.put(ResultMsgConstants.ERR_MSG, "调用idealer接口失败");
                    return result;
                }
            } else {
                return resultMQ;
            }
            
        } catch (Exception e) {
        	logger.error("saveGetOrSendCar ====> " + e);
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "系统繁忙,请稍后重试。");
            return result;
        }
		return result;
	}
	private void updateGetSend(String s,Integer f){
	      if (f == 10180001) {
	          TtReservation re = new TtReservation();
	          re.setGetsendFlag(2);
	          Example e = new Example(TtReservation.class);
	          Criteria criteria = e.createCriteria();
	          criteria.andEqualTo("oddNumber", s);
	          ttReservationMapper.updateByExampleSelective(re, e);
	      } else if(f == 10180002){
	    	  TtMaintenanceRecord re = new TtMaintenanceRecord();
	          re.setDrivingStatus("2");
	          Example e = new Example(TtMaintenanceRecord.class);
	          Criteria criteria = e.createCriteria();
	          criteria.andEqualTo("oddNumber", s);
	          ttMaintenanceRecordMapper.updateByExampleSelective(re, e);
	      }
	}
	/**
	 * 向idealer下单，并微信支付
	 * @param gscReservation
	 * @return
	 */
	public Map<String, Object> saveWxOrder(String pkId){
		logger.info("GetCarService.saveWxOrder==>start...");
		Map<String, Object> result = new HashMap<>();
		
		result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		TtEtco etco = ttEtcoMapper.selectByPrimaryKey(Long.valueOf(pkId));
		Integer flag = etco.getGetsendFlag();// 取送类型
		if(CheckUtil.NullOrEmpty(etco)){
			result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "订单不存在！");
            return result;
		}
		
        try {
        	//向idealer下单
            Map<String, Object> getCarMap = new HashMap<>();
            // 渠道号默认设置
            // 业务服务类别
            getCarMap.put("serviceType", "10071001");
            // 经销商代码
            getCarMap.put("dealerCode", idealerCode);
            // 车牌号
            getCarMap.put("plateNumber", etco.getLicenseNo());
            // 经销商代码类型
            getCarMap.put("dealerType", "10081002");
            // 消息来源
            getCarMap.put("msgSrc", "10091001");
            // 来源单据类型
            getCarMap.put("billType", "10101001");
            // 支付类型
            getCarMap.put("payer", "10461001");
            getCarMap.put("msgSrcService", etco.getMsgSrcFlag());
            if(flag==10180001){
            	// 来源单据取送车 服务类型
                getCarMap.put("takeDeliveryType", "10481001");
                // 来源单据编号
                getCarMap.put("billNo", etco.getResnId());
            }else if(flag==10180002){
            	getCarMap.put("takeDeliveryType", "10481002");
            	// 来源单据编号
                getCarMap.put("billNo", etco.getOrderid());
            }else if(flag==10180003){
            	getCarMap.put("msgSrcService", "10180003");
            	getCarMap.put("takeDeliveryType", "10180003");
                getCarMap.put("billNo", "10180003");
            }
            // 取送车流水
            getCarMap.put("takeDeliveryId", pkId);
            // 优惠券编号
            //getCarMap.put("couponNo", "111");
            // 起始地
            getCarMap.put("startAddr", etco.getStartAddr());
            // 起始地联系人
            getCarMap.put("startLinkman", etco.getStartLinkman());
            // 起始地电话
            getCarMap.put("startPhone", etco.getStartPhone());
            // 目的地
            getCarMap.put("destAddr", etco.getDestAddr());
            // 目的地联系人
            getCarMap.put("destLinkman", etco.getDestLinkman());
            // 目的地电话
            getCarMap.put("destPhone", etco.getDestPhone());
            if(flag==10180003){
	            // 起始地联系人
	            getCarMap.put("startLinkman", "123");
	            // 目的地联系人
	            getCarMap.put("destLinkman", "111");
            }
            // getCarMap.put("startTime","2016-11-01 00:00:00");
            // 预约时间
            getCarMap.put("startTime", DateUtil.formateDate(etco.getWonderTime(), "yyyy-MM-dd HH:mm:ss"));
            // 下单人
            getCarMap.put("operator", etco.getCreatorId());
            // 发生时间
            getCarMap.put("occurtime", new Date().getTime());
            //生产支付成功的签名
            Map<String, Object> carMap = new HashMap<>();
            carMap.put("etcoId", pkId);
            logger.info("secretKey为："+secretKey+"   carMap:"+carMap);
            String okSign = CommonUtils.genSign(carMap, secretKey);
            // 成功页面地址
            getCarMap.put("okUrl", okUrl+pkId+"&urlSign="+okSign);
            logger.info("okUrl为："+getCarMap.get("okUrl").toString());
            // 取消页面地址
            getCarMap.put("cancelUrl", canceUrl);
            // 失败也面地址
            getCarMap.put("failUrl", failUrl);
            getCarMap.put("channel", channel);
            CommonUtils.generateSign(getCarMap, secretKey);
            logger.info("idealerRequest xiadan map = " + getCarMap);
            TtEtco etc = new TtEtco();
            etc.setDef1("2");//微信支付2
            Example ex = new Example(TtEtco.class);
            Criteria  criteria = ex.createCriteria();
            criteria.andEqualTo("pkEtcoId", pkId);
            ttEtcoMapper.updateByExampleSelective(etc, ex);
            //更新取送车按钮状态
            updateGetSend(etco.getSrvOrderNo(),etco.getGetsendFlag());
            logger.error("saveWxOrder return map====> " + getCarMap);
            result.put(ResultMsgConstants.QUERY_DATA, getCarMap);
        } catch (Exception e) {
        	logger.error("saveWxOrder ====> " + e);
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "签名生成失败");
            return result;
        }
		return result;
	}
	/**
	 * 向Idealer下单，微信支付成功后更新支付状态
	 * @return
	 */
	public Map<String, Object> updateWxState(String pkId,String sign){
		logger.info("GetCarService.updateWxState==>start...");
		Map<String, Object> result = new HashMap<>();
        // 成功页面地址
		TtEtco etco = ttEtcoMapper.selectByPrimaryKey(Long.valueOf(pkId));
		if(CheckUtil.NullOrEmpty(etco)){
			result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "订单不存在！");
            return result;
		}
		Map<String, Object> carMap = new HashMap<>();
        carMap.put("etcoId", pkId);
        String okSign ="";
		try {
			logger.info("secretKey为："+secretKey+"   carMap:"+carMap);
			okSign = CommonUtils.genSign(carMap, secretKey);
            logger.info("okSign为："+okSign);
		} catch (NoSuchAlgorithmException e1) {
			logger.info("updateWxState==>error..."+e1.getMessage(),e1);
			result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "签名异常");
            return result;
		}
		if(!sign.equals(okSign)){
			logger.info("sign为："+sign);
			result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "签名不正确");
            return result;
		}
		TtEtco etco1 = new TtEtco();
		etco1.setPkEtcoId(Long.valueOf(pkId));
		etco1.setGetsendStatus(10191002);
		ttEtcoMapper.updateByPrimaryKeySelective(etco1);
		result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		result.put(ResultMsgConstants.ERR_MSG, "下单成功");
		return result;
	}
	/** 
	 * 取消取送车的逻辑
	 * 1.需要判断sa是否已下单
	 * 如果sa已经下单 就要调用idealers的接口来取消
	 * 如果sa没有下单 就直接在我们这取消
	 * 优惠券使用状态回滚
	 */
    public Map<String, Object> cancelCar(TtEtco etco, String dr) {
        Map<String, Object> cancelResult = new HashMap<>();
        cancelResult.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
        if (etco != null) {
            // 取送车类型
            String getSendType = etco.getGetsendFlag() == 10180001? "取车订单" :etco.getGetsendFlag() == 10180002? "送车订单":"代驾订单";
            // 2016.11.03修改如果本来就是取消下单的取送车单，也要更新dr=1
            if (etco.getGetsendStatus() != null
                    && (GetCarConstant.GETSEND_STATUS_10191001.equals(etco.getGetsendStatus().toString()) 
                    		|| GetCarConstant.GETSEND_STATUS_10191005.equals(etco.getGetsendStatus().toString()) )) {
            	TtEtco etcoPo = new TtEtco();
            	etcoPo.setPkEtcoId(etco.getPkEtcoId());
            	etcoPo.setDr(Short.valueOf(dr));
            	etcoPo.setGetsendStatus(Integer.valueOf(GetCarConstant.GETSEND_STATUS_10191005));
            	etcoPo.setEtcoStatus(10041005);
            	etcoPo.setCouponId("");
            	ttEtcoMapper.updateByPrimaryKeySelective(etcoPo);
                updateResnInfo(etco);
                if(GetCarConstant.GETSEND_STATUS_10191001.equals(etco.getGetsendStatus().toString())){
                	logger.info("订单取消====>订单状态:"+etco.getGetsendStatus()+"  开始返还积分。。。");
                	Map<String, Object> resultMQ = mqUserPoints(etco,EventBizStep.GETSEND_ORDER_ADD);
                	if ("1".equals(resultMQ.get("resultCode").toString())) {
                		logger.info("积分返还成功====> ");
                	}else{
                		logger.info("积分返还失败====> " + resultMQ.get("errMsg"));
                	}
                }
            } else {
                // 进行取消操作
                Map<String, Object> cancalMap = new HashMap<>();
                cancalMap.put("serviceType", "10071001");
                cancalMap.put("dealerType", "10081002");
                cancalMap.put("dealerCode", idealerCode);
                cancalMap.put("msgSrc", "10091001");
                cancalMap.put("cancelType", "10111001");
                cancalMap.put("occurtime", new Date().getTime());
                if (!CheckUtil.NullOrEmpty(etco.getIdealersid())) {
                    cancalMap.put("idealersId", etco.getIdealersid());
                }
                String idealerResponse = null;
                JSONObject returnObject = null;
                try {
                    idealerResponse = idealerssService.cancelOrder(cancalMap);
                    logger.info("idealerResponse cancel = " + idealerResponse);
                    returnObject = JSONObject.fromObject(idealerResponse);
                } catch (Exception e) {
                    logger.error("调用取消取送车订单接口失败：", e);
                    cancelResult.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
                    cancelResult.put(ResultMsgConstants.ERR_MSG, "送车订单代驾已派单，已不能在线修改，请联系客服400-821-8778");
                    return cancelResult;
                }
                // 如果调用接口失败
                if (returnObject == null || returnObject.get("code") == null) {
                	cancelResult.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
                    cancelResult.put(ResultMsgConstants.ERR_MSG, "送车订单代驾已派单，已不能在线修改，请联系客服400-821-8778");
                    return cancelResult;
                }
                // 取消成功
                else if ("91200".equals(returnObject.get("code").toString())) {
                    // 取消成功
                    // 更新自己的状态
                	// 解绑优惠券
                	TtEtco etco1 = new TtEtco();
                	etco1.setDr(Short.valueOf(dr));
                	etco1.setGetsendStatus(Integer.valueOf(GetCarConstant.GETSEND_STATUS_10191005));
                	etco1.setEtcoStatus(10041005);
                	etco1.setCouponId("");
                	Example ex = new Example(TtEtco.class);
                	Criteria criteria = ex.createCriteria();
                	criteria.andEqualTo("pkEtcoId",etco.getPkEtcoId());
                	criteria.andEqualTo("dr",0);
                	ttEtcoMapper.updateByExampleSelective(etco1, ex);
                    updateResnInfo(etco);
                    logger.info("订单取消====>订单状态:"+etco.getGetsendStatus()+"  开始返还积分。。。");
                	Map<String, Object> resultMQ = mqUserPoints(etco,EventBizStep.GETSEND_ORDER_ADD);
                	if ("1".equals(resultMQ.get("resultCode").toString())) {
                		logger.info("积分返还成功====> ");
                	}else{
                		logger.info("积分返还失败====> " + resultMQ.get("errMsg"));
                	}
                }
                // 取消失败
                else {
                	logger.error("调用取消取送车订单接口失败："+ getSendType + returnObject.get("message"));
                	cancelResult.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
                    cancelResult.put(ResultMsgConstants.ERR_MSG, "送车订单代驾已派单，已不能在线修改，请联系客服400-821-8778");
                    return cancelResult;
                }
            }
            // 取消操作成功之后，返还优惠券
//            if(!CheckUtil.NullOrEmpty((String)queryMap.get("COUPON_ID"))){
//            	logger.debug("取消操作，返回取送车优惠券："+queryMap.get("COUPON_ID"));
//                discountTicketService.updateCouponStatusByCouponIds(null, 1, (String)queryMap.get("COUPON_ID"));
//            }
            cancelResult.put(ResultMsgConstants.RESULT_MESSAGE, getSendType + "取消成功");
        }
        return cancelResult;
    }
    /**
	 * 取消之后 重新计算预约单的取送车类型
	 * @param etco
	 */
    public void updateResnInfo(TtEtco etco) {
        // 如果是保养预约关联的取送车订单
        if(etco != null && etco.getResnId() != null){
        	TtEtco et = new TtEtco();
        	et.setResnId(etco.getResnId());
        	et.setDr((short) 0);
        	List<TtEtco> l = ttEtcoMapper.select(et);
        	Integer getSendType = 0;
            if (l != null && !l.isEmpty()) {
                for (TtEtco m : l) {
                    getSendType += m.getGetsendFlag();
                }
            }
            Integer getSendTypeString = getSendType > 10180002 ? 10180003 : getSendType;
            TtReservation res = new TtReservation();
            res.setResnId(Integer.valueOf(etco.getResnId().toString()));
            res.setGetsendFlag(getSendTypeString);
            ttReservationMapper.updateByPrimaryKeySelective(res);
        }
    }
    /**
	 * 取消取送车
	 * @param etcoId
	 */
    public Map<String, Object> cancelGetSendCar(String etcoId) {
    	TtEtco etco = ttEtcoMapper.selectByPrimaryKey(Long.valueOf(etcoId));
    	
    	return cancelCar(etco, "1");
    }
    /**
	 * 取送车 快捷获取地址
	 * @param searchType
	 */
    public Map<String, Object> searchAddr(Integer searchType,String userId) {
    	Map<String, Object> result = new HashMap<>();
    	if(searchType==1){
    		String addr = ttEtcoMapper.findDealerAddr(userId);
    		Map<String, String> data = new HashMap<>();
    		data.put("addr", addr==null?"":addr);
    		data.put("addrType", "1");
    		result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
        	result.put(ResultMsgConstants.RESULT_DATA, data);
    	}else if(searchType==2){
    		String addr = ttEtcoMapper.findHomeAddr(userId);
    		Map<String, String> data = new HashMap<>();
    		data.put("addr", addr==null?"":addr);
    		data.put("addrType", "2");
    		result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
        	result.put(ResultMsgConstants.RESULT_DATA, data);
    	}else{
    		result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_DATA, "");
        	result.put(ResultMsgConstants.ERR_MSG, "地址信息不存在");
    	}
    	return result;
    }
    /**
	 * 取送车 获取历史地址
	 * @param addrName
	 * @param userId
	 */
    public List<Map<String, Object>> searchHistory(String addrName,String userId) {
    	List<Map<String, Object>>  list = new ArrayList<>();
    	list = ttEtcoMapper.querySearchHistory("%"+addrName+"%", userId);
    	
    	return list;
    }
    /**
	 * 取送车 取送（车）订单列表
	 * @param userId
	 */
    public List<Map<String, Object>> queryCar(String userId) {
    	List<Map<String, Object>>  list = new ArrayList<>();
    	list = ttEtcoMapper.queryQscList(Integer.valueOf(userId));
    	
    	return list;
    }
    /**
	 * 取送车 取送（车）订单详情
	 * @param etcoId
	 */
    public Map<String, Object> queryQscDetail(String etcoId) {
    	Map<String, Object>  list = new HashMap<>();
    	list = ttEtcoMapper.queryQscDetail(Integer.valueOf(etcoId));
    	
    	return list;
    }
    /**
	 * 我的取送车  查看进度
	 * @param etcoId
     * @throws NoSuchAlgorithmException 
	 */
    public Map<String, Object> queryQscProgress(String etcoId) throws NoSuchAlgorithmException {
    	Map<String, Object>  result = new HashMap<>();
    	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
    	TtEtco etco = ttEtcoMapper.selectByPrimaryKey(Long.valueOf(etcoId));
    	
        // 各派单节点时间
    	JSONArray nodeTime = null;
        if (etco != null) {
            // 派单状态变更履历
            nodeTime = JSONArray.fromObject(CheckUtil.NullOrEmpty(etco.getEtcoStatusHistory()) ? "[]" : "["+ etco.getEtcoStatusHistory() + "]");
        } else {
        	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "未查询到对应的取送车订单");
            return result;
        }
        result.put("get_car_code", etco.getGetCarCode());// 接车验证码
        result.put(ResultMsgConstants.RESULT_DATA, nodeTime);
        result.put("etco", etco);
    	
    	return result;
    }
    /**
	 * 我的取送车  司机信息
	 * @param etcoId
     * @throws NoSuchAlgorithmException 
	 */
    public Map<String, Object> queryDriverinfo(String etcoId) throws NoSuchAlgorithmException {
    	Map<String, Object>  result = new HashMap<>();
    	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
    	TtEtco etco = ttEtcoMapper.selectByPrimaryKey(Long.valueOf(etcoId));
    	Map<String, Object> map = new HashMap<>();
        map.put("occurtime", new Date().getTime());
        map.put("idealersId", etco.getIdealersid());
        map.put("serviceType", "10071001");
        String returnJsonCode = "";
		try {
			logger.info("idealerRequest xiadan map = " + map);
			returnJsonCode = idealerssService.driverInfo(map);
		} catch (Exception e) {
			logger.error("调用司机信息接口失败：", e);
            result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
        	result.put(ResultMsgConstants.RESULT_MESSAGE, e.getMessage());
            return result;
		}
        String driverNo = "";
        String driverPhone = "";
        String driverPicture = "";
        if (returnJsonCode != null && !"".equals(returnJsonCode)) {
            JSONObject returnObject = JSONObject.fromObject(returnJsonCode);
            if (returnObject != null && returnObject.get("code").equals("91200")) {
                JSONObject resultMsg = JSONObject.fromObject(returnObject.get("data"));
                TtEtco etc = new TtEtco();
                etc.setPkEtcoId(Long.valueOf(etcoId));
                driverNo = "null".equals(resultMsg.getString("driverNo"))?"":resultMsg.getString("driverNo");
                driverPhone = "null".equals(resultMsg.getString("driverPhone"))?"":resultMsg.getString("driverPhone");
                driverPicture = "null".equals(resultMsg.getString("driverPicture"))?"":resultMsg.getString("driverPicture");
                etc.setDriverNo(driverNo);
                etc.setDriverPhone(driverPhone);
                etc.setDriverName("null".equals(resultMsg.getString("driverName"))?"":resultMsg.getString("driverName"));
                etc.setDriverPicture(driverPicture);
                etc.setDriverLevel("null".equals(resultMsg.getString("driverLevel"))?"":resultMsg.getString("driverLevel"));
                etc.setDriverIdCard("null".equals(resultMsg.getString("driverIdCard"))?"":resultMsg.getString("driverIdCard"));
                etc.setDriverYear("null".equals(resultMsg.getString("driverYear"))?"":resultMsg.getString("driverYear"));
                etc.setDriverServiceTimes("null".equals(resultMsg.getString("driverServiceTimes"))?"":resultMsg.getString("driverServiceTimes"));
                ttEtcoMapper.updateByPrimaryKeySelective(etc);
                result.put("driverPicture", driverPicture);// 头像
                result.put("driverNo", driverNo);// 工号
                result.put("driverPhone", driverPhone);// 电话
            } else {
                result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
            	result.put(ResultMsgConstants.RESULT_MESSAGE, returnObject.get("message"));
                return result;
            }
        }
    	
    	return result;
    }
    /**
	 * 我的取送车   查看轨迹信息
	 * @param etcoId
     * @throws NoSuchAlgorithmException 
	 */
    public Map<String, Object> queryQscTrack(String etcoId) throws NoSuchAlgorithmException {
    	Map<String, Object>  result = new HashMap<>();
    	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
    	TtEtco etco = ttEtcoMapper.selectByPrimaryKey(Long.valueOf(etcoId));
    	String idealersId = etco.getIdealersid().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("occurtime", new Date().getTime());
        map.put("idealersId", idealersId);
        map.put("serviceType", "10071001");
        String returnJsonCode = "";
		try {
			logger.info("idealerRequest xiadan map = " + map);
			returnJsonCode = idealerssService.trackOrder(map);
		} catch (Exception e) {
			logger.error("调用轨迹信息接口失败：", e);
            result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
        	result.put(ResultMsgConstants.RESULT_MESSAGE, e.getMessage());
            return result;
		}
        if (returnJsonCode != null && !"".equals(returnJsonCode)) {
            JSONObject returnObject = JSONObject.fromObject(returnJsonCode);
            if (returnObject != null && returnObject.get("code").equals(91200)) {
                JSONObject resultMsg = JSONObject.fromObject(returnObject.get("data"));
                result.put(ResultMsgConstants.RESULT_DATA, resultMsg);
            } else {
                result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
            	result.put(ResultMsgConstants.RESULT_MESSAGE, returnObject.get("message"));
                return result;
            }
        }
    	
    	return result;
    }
    /**
	 * 我的取送车  更新订单进度和司机进度
	 * @param etcoId
	 */
    public Map<String, Object> qscStatus(Map<String, Object> param) {
    	Map<String, Object>  result = new HashMap<>();
    	Map<String, Object> ch = checkNull(param);
    	if("0".equals(ch.get("code").toString())){
    		return ch;
    	}
    	result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_SUCCESS);
    	String id = param.get("takeDeliveryId").toString();
    	TtEtco etcPo = new TtEtco();
    	etcPo.setPkEtcoId(Long.valueOf(id));
    	TtEtco etco = ttEtcoMapper.selectOne(etcPo);
    	if(CheckUtil.NullOrEmpty(etco)){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "失败，该订单不存在");
    		return result;
    	}
    	TtEtco etc = new TtEtco();
    	etc.setPkEtcoId(Long.valueOf(param.get("takeDeliveryId").toString()));
    	Integer orderStatus = Integer.valueOf(param.get("orderStatus").toString());
    	Integer driverStatus = Integer.valueOf(param.get("driverStatus").toString());
    	etc.setGetsendStatus(orderStatus(orderStatus));
    	etc.setEtcoStatus(driverStatus(driverStatus));
    	etc.setPreId(param.get("preId")==null?"":param.get("preId").toString());
    	if(driverStatus==0){
    		Long time = Long.valueOf(param.get("creationtime").toString());
    		String now = DateUtil.formateLong(time, "yyyy/MM/dd HH:mm");
    		String statusHistory = ",{\"status\":10041000,\"maker\":\"正在为您安排司机请耐心等待\",\"date\":\"" + now.substring(0, 10) + "\",\"time\":\""
                    + now.substring(11) + "\"}";
    		String sta = etco.getEtcoStatusHistory();
    		etc.setIdealersid(Long.valueOf(param.get("idealersId").toString()));
    		etc.setEtcoStatusHistory(sta+statusHistory);
    	}else if(driverStatus==10041002){
    		String idealersId = etco.getIdealersid().toString();
            Map<String, Object> map = new HashMap<>();
            map.put("occurtime", new Date().getTime());
            map.put("idealersId", idealersId);
            map.put("serviceType", "10071001");
            String returnJsonCode = "";
			try {
				logger.info("idealerRequest xiadan map = " + map);
				returnJsonCode = idealerssService.driverInfo(map);
			} catch (Exception e) {
				logger.error("调用司机信息接口失败：", e);
	            result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
	        	result.put(ResultMsgConstants.RESULT_MESSAGE, e.getMessage());
	            return result;
			}
            String driverName = "";
            if (returnJsonCode != null && !"".equals(returnJsonCode)) {
                JSONObject returnObject = JSONObject.fromObject(returnJsonCode);
                if (returnObject != null && returnObject.get("code").equals(91200)) {
                    JSONObject resultMsg = JSONObject.fromObject(returnObject.get("data"));
                    driverName = "null".equals(resultMsg.getString("driverName"))?"":resultMsg.getString("driverName");
                    etc.setDriverNo("null".equals(resultMsg.getString("driverNo"))?"":resultMsg.getString("driverNo"));
                    etc.setDriverPhone("null".equals(resultMsg.getString("driverPhone"))?"":resultMsg.getString("driverPhone"));
                    etc.setDriverName(driverName);
                    etc.setDriverPicture("null".equals(resultMsg.getString("driverPicture"))?"":resultMsg.getString("driverPicture"));
                    etc.setDriverLevel("null".equals(resultMsg.getString("driverLevel"))?"":resultMsg.getString("driverLevel"));
                    etc.setDriverIdCard("null".equals(resultMsg.getString("driverIdCard"))?"":resultMsg.getString("driverIdCard"));
                    etc.setDriverYear("null".equals(resultMsg.getString("driverYear"))?"":resultMsg.getString("driverYear"));
                    etc.setDriverServiceTimes("null".equals(resultMsg.getString("driverServiceTimes"))?"":resultMsg.getString("driverServiceTimes"));
                } else {
                    result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
                	result.put(ResultMsgConstants.RESULT_MESSAGE, returnObject.get("message"));
                    return result;
                }
            }
            Long time = param.get("driverAcceptDate")==null?0:Long.valueOf(param.get("driverAcceptDate").toString());
    		String now = DateUtil.formateLong(time, "yyyy/MM/dd HH:mm");
    		String statusHistory = ",{\"status\":10041002,\"maker\":\"已为您安排司机"+driverName+"（详情点击查看）到达前会与您联系，请保持电话畅通\","
    				+ "\"date\":\"" + now.substring(0, 10) + "\",\"time\":\""+ now.substring(11) + "\"}";
    		String sta = etco.getEtcoStatusHistory();
    		etc.setEtcoStatusHistory(sta+statusHistory);
    	}else if(driverStatus==10041003){
    		Long time = param.get("driverArriveDate")==null?0:Long.valueOf(param.get("driverArriveDate").toString());
    		String now = DateUtil.formateLong(time, "yyyy/MM/dd HH:mm");
    		String statusHistory = ",{\"status\":10041003,\"maker\":\"司机已就位\","
    				+ "\"date\":\"" + now.substring(0, 10) + "\",\"time\":\""+ now.substring(11) + "\"}";
    		String sta = etco.getEtcoStatusHistory();
    		etc.setEtcoStatusHistory(sta+statusHistory);
    	}else if(driverStatus==10041004){
    		Long time = param.get("driverDriveDate")==null?0:Long.valueOf(param.get("driverDriveDate").toString());
    		String now = DateUtil.formateLong(time, "yyyy/MM/dd HH:mm");
    		String statusHistory = ",{\"status\":10041004,\"maker\":\"司机开始驾车至 "+etco.getDestAddr()+"\","
    				+ "\"date\":\"" + now.substring(0, 10) + "\",\"time\":\""+ now.substring(11) + "\"}";
    		String sta = etco.getEtcoStatusHistory();
    		etc.setEtcoStatusHistory(sta+statusHistory);
    	}else if(driverStatus==50){
    		String str = "司机已送达至 "+etco.getDestAddr();
    		if(etco.getGetsendFlag()==10180001){
    			Map<String, Object> sa = ttEtcoMapper.findSaInfo(etco.getSrvOrderNo());
    			str += "服务顾问 " +sa.get("USER_NAME") +"  "+ sa.get("PHONE")+ "已接收车辆";
    		}else{
    			str += "  " +etco.getCreator() +"  "+ etco.getDestPhone() + "已接收车辆";
    		}
    		Long time = param.get("driverFinishDate")==null?0:Long.valueOf(param.get("driverFinishDate").toString());
    		String now = DateUtil.formateLong(time, "yyyy/MM/dd HH:mm");
    		String statusHistory = ",{\"status\":10041050,\"maker\":\""+str+"\","
    				+ "\"date\":\"" + now.substring(0, 10) + "\",\"time\":\""+ now.substring(11) + "\"}";
    		String sta = etco.getEtcoStatusHistory();
    		etc.setEtcoStatusHistory(sta+statusHistory);
    	}
    	int i = ttEtcoMapper.updateByPrimaryKeySelective(etc);
        if (i==1) {
            return result;
        } else {
        	result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
        	result.put(ResultMsgConstants.RESULT_MESSAGE, "调用成功，更新失败");
            return result;
        }
    }
    /**
	 *  校验参数是否为空
	 */
    public Map<String, Object> checkNull(Map<String, Object> param) {
    	Map<String, Object>  result = new HashMap<>();
    	result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_SUCCESS);
    	if(CheckUtil.NullOrEmpty(param.get("sign"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "签名不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("idealersId"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "平台服务单号不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("orderStatus"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "预约单状态不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("driverStatus"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "司机派单状态不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("creationtime"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "推送产生时间不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("postLogId"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "推送 id 不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("msgSrc"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "消息来源不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("dealerType"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "经销商代码类型不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("dealerCode"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "经销商代码不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("occurtime"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "发生时间不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("channel"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "渠道号不能为空");
    		return result;
    	}
    	if(CheckUtil.NullOrEmpty(param.get("takeDeliveryId"))){
    		result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
    		result.put(ResultMsgConstants.RESULT_MESSAGE, "取送车流水不能为空");
    		return result;
    	}
    	try {
    		String sign = param.get("sign")==null ? "":param.get("sign").toString();
    		logger.info("idealer---sign===" + sign);
    		param.remove("sign");
    		param.put("channel", "100");
			Map<String, Object> map = CommonUtils.generateSign(param, secretKeyStatus);
			String si = map.get("sign").toString();
			logger.info("localhost---sign===" + si);
			if(!si.equals(sign)){
				result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
				result.put(ResultMsgConstants.RESULT_MESSAGE, "加密不正确");
			}
		} catch (NoSuchAlgorithmException e) {
			logger.info("checkNull===" + e);
			result.put(ResultMsgConstants.RESULT_MSG_CODE, ResultMsgConstants.RESULT_MSG_CODE_ERROR);
			result.put(ResultMsgConstants.RESULT_MESSAGE, e.getMessage());
		}
    	return result;
    }
    /**
	 * 我的取送车  订单进度
	 * @param etcoId
	 */
    public Integer orderStatus(Integer pa) {
    	if(pa==10031001){
    		return 10191002;
    	}else if(pa==10031002){
    		return 10191003;
    	}else if(pa==10031003){
    		return 10191004;
    	}else if(pa==10031004){
    		return 10191005;
    	}else if(pa==10031005){
    		return 10191006;
    	}else if(pa==10031006){
    		return 10191007;
    	}
    	return 0;
    }
    /**
	 * 我的取送车  司机进度
	 * @param etcoId
	 */
    public Integer driverStatus(Integer pa) {
    	if(pa==0){
    		return 10041000;
    	}else if(pa==5){
    		return 10041005;
    	}else if(pa==50){
    		return 10041050;
    	}else if(pa==10041001){
    		return 10041001;
    	}else if(pa==10041002){
    		return 10041002;
    	}else if(pa==10041003){
    		return 10041003;
    	}else if(pa==10041004){
    		return 10041004;
    	}
    	return -1;
    }
    public GscReservation toTi() {
    	GscReservation g = new GscReservation();
    	g.setModel("车型");
    	g.setLicenseNo("车牌号");
    	g.setDestDate("预约时间");
    	g.setGetSendAddr("取车地址");
    	g.setGetSendAddrType("取车地址类型");
    	g.setGetUserPhone("接车人电话");
    	g.setBournAddr("目的地");
    	g.setBournAddrType("目的地类型");
    	g.setPhone("联系电话");
    	g.setSrvOrderNo("预约单号");
    	
    	return g;
    }
    /**
	 * 判断距离是否超出服务范围
	 * @param etco
	 */
    public Map<String, Object> validateGscDistance(GscReservation gscReservation,String userId) {
    	Map<String, Object> result = new HashMap<>();
    	Map<String, Object> validateMap = new HashMap<>();
    	String param = "";
    	if(!CheckUtil.NullOrEmpty(gscReservation) && !CheckUtil.NullOrEmpty(gscReservation.getGetSendFlag()) 
    			&&GetCarConstant.GETSEND_FLAG_10180003.equals(gscReservation.getGetSendFlag())){
    		//代驾入参校验
    		param = MapConverUtil.NotNullPO2Map(gscReservation,toTi(), "coupons","srvOrderNo");
    	}else{
    		//养修预约、工单入参校验
    		param = MapConverUtil.NotNullPO2Map(gscReservation,toTi(), "coupons");
    	}
    	if(!CheckUtil.NullOrEmpty(param)){
    		result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
    		result.put(ResultMsgConstants.ERR_MSG, param);
            return result;
    	}
    	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
    	Map<String, Object> memberDto = ttEtcoMapper.queryMember(userId);
    	String nickName = memberDto==null?"":memberDto.get("nickName")==null?"":memberDto.get("nickName").toString();
    	
    	Integer flag = gscReservation.getGetSendFlag();// 取送类型
        String srvOrderNo = gscReservation.getSrvOrderNo();// 预约单号
        //预约时间  限定晚于当前系统时间，并早于养修预约时间
        String destDate = gscReservation.getDestDate();
        
        // 销售店代码
        String dealerCode = null;
        TtReservation re = null;
        TtMaintenanceRecord mRecord = null;
        if(flag!=10180003){
	        TtReservation rePo = new TtReservation();
	        rePo.setOddNumber(srvOrderNo);
	        re = ttReservationMapper.selectOne(rePo);
	        // 根据工单号查询销售店代码和工单状态
	    	TtMaintenanceRecord record = new TtMaintenanceRecord();
	    	record.setOddNumber(srvOrderNo);
	    	mRecord = ttMaintenanceRecordMapper.selectOne(record);
        }
        // 存在保养预约ID的取送车订单
        if(flag==10180001 && !CheckUtil.NullOrEmpty(re)){
            if (re != null && GetCarConstant.APPLY_STATUS_10011005.equals(re.getApplyStatus())) {
            	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            	result.put(ResultMsgConstants.ERR_MSG, "预约单已经取消");
                return result;
            } else {
                dealerCode = re == null? "" : re.getDealerCode();
            }
        } else if(flag==10180002 && !CheckUtil.NullOrEmpty(mRecord)){
//            if("3".equals(mRecord.getRepairStatus().toString())){
//                // 工单已交车完成，不能再送车下单
//            	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
//            	result.put(ResultMsgConstants.ERR_MSG, "该订单关联的维修工单已交车完成，下单失败");
//                return result;
//            } else {
                dealerCode = mRecord.getDealerCode();
//            }
        } else if(flag==10180003){
        	logger.info("GetCarService...下单类型为代驾："+flag);
        } else{
        	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "该订单无法关联保养预约或维修工单，下单失败！");
            return result;
        }
        logger.info("销售店代码 >>> dealerCode === " + dealerCode);
        TmDealer d = null;
        if(flag!=10180003){
        	TmDealer dea = new TmDealer();
            dea.setDealerCode(dealerCode);
            d = tmDealerMapper.selectOne(dea);
        }
        //用户提交时检查该店取送车功是否开启/关闭状态
        if(d != null){
            // 销售店是否开通取送车功能
            String gscDealserFlag = d.getGscDealerFlag()==null?"":d.getGscDealerFlag().toString();
            logger.info("是否开通取送车功能0：关闭; 1：开启 >>> gscDealserFlag === " + gscDealserFlag);
            if (!"1".equals(gscDealserFlag)) {
            	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            	result.put(ResultMsgConstants.ERR_MSG, "非常抱歉，销售店暂时不能提供取送车服务");
                return result;
            }
        }
        
        if(destDate==null ||"".equals(destDate)){
        	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "预约时间不能为空");
            return result;
        }else if(dealerCode!=null){
        	//校验经销商的服务时间
        	Map<String, Object> gscTime = ttEtcoMapper.findGscTime(dealerCode);
        	if(gscTime!=null && !gscTime.isEmpty()){
        		Integer t = Integer.valueOf(destDate.substring(11,13)+destDate.substring(14,16));
        		logger.info("预约时间 >>> destDate:" + destDate  +"  t:"+t);
        		if(flag==10180001){
        			Integer gcs = gscTime.get("GC_START")==null?0:Integer.valueOf(gscTime.get("GC_START").toString());
        			Integer gce = gscTime.get("GC_END")==null?0:Integer.valueOf(gscTime.get("GC_END").toString());
        			if(t<gcs||t>gce){
        				result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	        	result.put(ResultMsgConstants.ERR_MSG, "经销商接受预约时间范围："+gscTime.get("GC_TIME"));
        	            return result;
        			}
                }else if(flag==10180002){
        			Integer scs = gscTime.get("SC_START")==null?0:Integer.valueOf(gscTime.get("SC_START").toString());
        			Integer sce = gscTime.get("SC_END")==null?0:Integer.valueOf(gscTime.get("SC_END").toString());
        			if(t<scs||t>sce){
        				result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	        	result.put(ResultMsgConstants.ERR_MSG, "经销商接受预约时间范围："+gscTime.get("SC_TIME"));
        	            return result;
        			}
                }
        	}
        }
        Date dest = DateUtil.dateFormat(destDate, "yyyy-MM-dd HH:mm:ss");
        Date now1 = new Date();
        if(GetCarConstant.GETSEND_FLAG_10180001.equals(flag)){
        	if(DateUtil.beforDate(dest, now1) || DateUtil.afterDate(dest, re.getReseApplStartTime()) ){
            	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            	result.put(ResultMsgConstants.ERR_MSG, "预约时间  晚于当前系统时间，并早于养修预约时间");
                return result;
            }
        }
        
        // 渠道号默认设置
        // 业务服务类别
        validateMap.put("serviceType", "10071001");
        // 经销商代码
        validateMap.put("dealerCode", idealerCode);
        // 车牌号
        validateMap.put("plateNumber", gscReservation.getLicenseNo());
        // 经销商代码类型
        validateMap.put("dealerType", "10081002");
        // 消息来源
        validateMap.put("msgSrc", "10091001");
        // 来源单据类型
        validateMap.put("billType", "10101001");
        // 支付类型
        validateMap.put("payer", "10461001");
        validateMap.put("msgSrcService", gscReservation.getMsgSrcService());
        if(flag==10180001){
        	// 来源单据取送车 服务类型
        	validateMap.put("takeDeliveryType", "10481001");
            // 来源单据编号
        	validateMap.put("billNo", re.getResnId());
        }else if(flag==10180002){
        	validateMap.put("takeDeliveryType", "10481002");
        	// 来源单据编号
        	validateMap.put("billNo", mRecord.getMaintenanceWorkOrderNum());
        }else if(flag==10180003){
        	validateMap.put("msgSrcService", "10180003");
        	validateMap.put("takeDeliveryType", "10180003");
        	validateMap.put("billNo", "10180003");
        }
        // 取送车流水
        validateMap.put("takeDeliveryId", "123");
        // 优惠券编号
        validateMap.put("coupon_No", "111");
        if(flag==10180001){
            // 起始地
        	validateMap.put("startAddr", gscReservation.getGetSendAddr());
            // 起始地联系人
            validateMap.put("startLinkman", "".equals(nickName)?"123":nickName);
            // 起始地电话
            validateMap.put("startPhone", gscReservation.getPhone());
            // 目的地
            validateMap.put("destAddr", gscReservation.getBournAddr());
            // 目的地联系人
            validateMap.put("destLinkman", re.getGetsendcarName());
            // 目的地电话
            validateMap.put("destPhone", re.getGetsendcarPhone());
        }else if(flag==10180002){
        	// 起始地
        	validateMap.put("startAddr", gscReservation.getGetSendAddr());
            // 起始地联系人
            validateMap.put("startLinkman", mRecord.getGetsendcarName());
            // 起始地电话
            validateMap.put("startPhone", mRecord.getGetsendcarPhone());
            // 目的地
            validateMap.put("destAddr", gscReservation.getBournAddr());
            // 目的地联系人
            validateMap.put("destLinkman", "".equals(nickName)?"123":nickName);
            // 目的地电话
            validateMap.put("destPhone", gscReservation.getGetUserPhone());
        }else if(flag==10180003){
        	// 起始地
        	validateMap.put("startAddr", gscReservation.getGetSendAddr());
            // 起始地联系人
            validateMap.put("startLinkman", "123");
            // 起始地电话
            validateMap.put("startPhone", gscReservation.getPhone());
            // 目的地
            validateMap.put("destAddr", gscReservation.getBournAddr());
            // 目的地联系人
            validateMap.put("destLinkman", "111");
            // 目的地电话
            validateMap.put("destPhone", gscReservation.getGetUserPhone());
        }
        // （取车/送车）时间（yyyy-MM-dd HH:mm:ss）
        validateMap.put("startTime", DateUtil.formateDate(DateUtil.dateFormat(gscReservation.getDestDate(), "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
        // 下单人
        validateMap.put("operator", userId);
        // 发生时间
        validateMap.put("occurtime", new Date().getTime());
        String returnDate = "";
        try {
            logger.info("取送车距离验证参数：" + validateMap);
            returnDate = idealerssService.validOrder(validateMap);
            logger.info("取送车距离验证返回结果：" + returnDate);

        } catch (Exception e) {
            logger.error("调用取送车距离验证接口失败：", e);
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, e.getMessage());
            return result;
        }
        JSONObject returnJson = JSONObject.fromObject(returnDate);
        // 如果调用接口失败
        if (returnJson == null || returnJson.get("code") == null) {
        	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
        	result.put(ResultMsgConstants.ERR_MSG, "验证订单接口调用失败");
            return result;
        }else if (returnJson.get("code").toString().equals("91200")) {
            JSONObject distanceJson = returnJson.getJSONObject("data");
            if (distanceJson != null && distanceJson.get("referKilometer") != null
            		&& distanceJson.get("referPrice") != null) {
                if (d!=null && d.getGscMaxMileage() != null && distanceJson.getDouble("referKilometer") > (Double.valueOf(d.getGscMaxMileage()) * 1000)) {
                	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
                	
                    String msg = "你选择的" + (flag== 10180001? "取车" :flag== 10180002? "送车":"代驾") + "地点超过本店的"
                            + d.getGscMaxMileage() + "公里服务里程范围";
                    result.put(ResultMsgConstants.ERR_MSG, msg);
                    return result;
                }else{
                	// 保存订单
                    String now = DateUtil.formateDate(new Date(), "yyyy/MM/dd HH:mm");
                    String etcoStatusHistory = "{\"status\":10041001,\"maker\":\"\",\"date\":\"" + now.substring(0, 10) + "\",\"time\":\""
                            + now.substring(11) + "\"}";
                    Long pkId = Long.valueOf(ttEtcoMapper.findPkEtcoId());
                    TtEtco et = new TtEtco();
                    et.setPkEtcoId(pkId);
                    if(flag==10180001){
                    	et.setResnId(Long.valueOf(re.getResnId()));
                    }else if(flag==10180002){
                    	et.setOrderid(mRecord.getMaintenanceWorkOrderNum());
                    }
                    et.setGetsendFlag(flag);
                    et.setGetsendStatus(Integer.valueOf(GetCarConstant.GETSEND_STATUS_10191001));
                    et.setCreatorId(Integer.valueOf(userId));
                    et.setCreator(nickName);
                    et.setSalemarketArr(d == null ? null : d.getDetailAddress());
                    et.setSalemarketName(d == null ? null : d.getDealerName());
                    et.setSalemarketTelephone(d == null ? null : d.getServiceHotline());
                    et.setWonderTime(dest);
                    et.setStartAddr(gscReservation.getGetSendAddr());
                    et.setStartAddrType("".equals(gscReservation.getGetSendAddrType())?0:Short.valueOf(gscReservation.getGetSendAddrType()));
                    et.setStartPhone(gscReservation.getPhone());
                    et.setDestAddr(gscReservation.getBournAddr());
                    et.setDestAddrType("".equals(gscReservation.getBournAddrType())?0:Short.valueOf(gscReservation.getBournAddrType()));
                    et.setDestPhone(gscReservation.getGetUserPhone());
                    if(flag==10180001){
                    	et.setStartLinkman(nickName);
                    	et.setDestLinkman(re.getGetsendcarName());
                    }else if(flag==10180002){
                    	et.setStartLinkman(mRecord.getGetsendcarName());
                    	et.setDestLinkman(nickName);
                    }
                    et.setSrvOrderNo(gscReservation.getSrvOrderNo());
                    et.setEtcoStatusHistory(etcoStatusHistory);
                    et.setCreationtime(new Date());
                    et.setLicenseNo(gscReservation.getLicenseNo());
                    et.setModelName(gscReservation.getModel());
                    //来源单据取送车 服务类型
                    et.setMsgSrcFlag(gscReservation.getMsgSrcService());
                    Double referKilometer = distanceJson.getDouble("referKilometer")/1000;
                    et.setReferkilometer(BigDecimal.valueOf(referKilometer));
                    et.setReferprice(BigDecimal.valueOf(distanceJson.getDouble("referPrice")));
                    ttEtcoMapper.insertSelective(et);
                	Map<String, Object> data = new HashMap<>();
                	data.put("referKilometer", referKilometer);
                	data.put("referPrice", distanceJson.getDouble("referPrice"));
                	data.put("etcoId", pkId);
                	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
                	result.put(ResultMsgConstants.QUERY_DATA, data);
                    return result;
                }
            } else {
            	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            	result.put(ResultMsgConstants.ERR_MSG, "验证订单接口调用失败");
                return result;
            }
        }
        // 验证失败
        else {
        	result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.ERR_MSG, returnJson.getString("message"));
            return result;
        }
    }
    
    /**
	 * 获取车主信息
	 */
    public Map<String, Object> getCarInfo(String userId) {
    	Map<String, Object> result = new HashMap<>();
    	Map<String, Object> re = ttEtcoMapper.queryMember(userId);
    	String seriesName = re==null?"":re.get("seriesName")==null?"":re.get("seriesName").toString();
    	String licenseNo = re==null?"":re.get("licenseNo")==null?"":re.get("licenseNo").toString();
    	String phone = re==null?"":re.get("phone")==null?"":re.get("phone").toString();
    	
    	result.put("seriesName", seriesName);
    	result.put("licenseNo", licenseNo);
    	result.put("phone", phone);
    	return result;
    }
}
